#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <QGraphicsItem>
#include <QGraphicsView>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

//    ui->download_progressBar->hide();
    open_flag = 0;
    start_flag = 0;
    packet_id = 0;
    timer.start(1000);

    connect(&timer, SIGNAL(timeout()), this, SLOT(timerOut_slot()));
    connect(&timer2, SIGNAL(timeout()), this, SLOT(timer2Out_slot()));
    connect(&serial, SIGNAL(readyRead()), this, SLOT(read_serial_slot()));

    flag = 0;
    close_flag = 1;
QGraphicsItem *item;
scene = new QGraphicsScene;
//    QGraphicsView *view = new QGraphicsView( scene,this );
    ui->graphicsView->setScene(scene);

//    scene->addPixmap(QPixmap("C:\\Users\\Administrator\\Desktop\\biny.png") );
 item=scene->addPixmap(QPixmap("biny.png"));
 item->setFlag(QGraphicsItem::ItemIsMovable);
 item->setScale(0.09); //默认加载比例
//scene->setSceneRect(-pix.width() / 2,-pix.height() / 2,pix.width(),pix.height());
    //    view->show();
//    ui->graphicsView->show();

//    QMovie *movie = new QMovie("C:\\Users\\Administrator\\Desktop\\biny.png");
//    ui->label_18->setMovie(movie);
//    movie->start();

//ui->graphicsView->setStyleSheet("outline: none");
ui->graphicsView->setStyleSheet("padding: -1");

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_serial_open_pushButton_clicked()
{
    if(open_flag == 0)
    {
        serial.setPortName(ui->serial_number_comboBox->currentText());
        serial.setBaudRate(ui->baud_rate_comboBox->currentText().toInt());
        switch(ui->parity_bit_comboBox->currentIndex())
        {
            case 0:
                serial.setParity(QSerialPort::NoParity); break;
            case 1:
                serial.setParity(QSerialPort::OddParity); break;
            case 2:
                serial.setParity(QSerialPort::EvenParity); break;
            case 3:
                serial.setParity(QSerialPort::MarkParity); break;
            case 4:
                serial.setParity(QSerialPort::SpaceParity); break;
            default:
                break;
        }
        switch(ui->data_bit_comboBox->currentIndex())
        {
            case  0:
                serial.setDataBits(QSerialPort::Data5); break;
            case  1:
                serial.setDataBits(QSerialPort::Data6); break;
            case  2:
                serial.setDataBits(QSerialPort::Data7); break;
            case  3:
                serial.setDataBits(QSerialPort::Data8); break;
            default:
                break;
        }
        switch(ui->stop_bit_comboBox->currentIndex())
        {
        case  0:
            serial.setStopBits(QSerialPort::OneStop); break;
        case  1:
            serial.setStopBits(QSerialPort::OneAndHalfStop); break;
        case  2:
            serial.setStopBits(QSerialPort::TwoStop); break;
        default:
            break;
        }
        serial.setFlowControl(QSerialPort::NoFlowControl);
        if(serial.open(QIODevice::ReadWrite) == true)
        {
            open_flag = 1;
            ui->serial_open_pushButton->setText(QString("关闭"));
            qDebug()<<"open success";
        }
        else
        {
            QMessageBox::warning(NULL, "warning", "串口不存在或者被其它应用程序占用！", "确定");
            qDebug()<<"open failed";
        }
        /* 烧录按钮使能 */
        ui->download_pushButton->setEnabled(true);
    }
    else
    {
        serial.close();
        ui->serial_open_pushButton->setText(QString("打开"));
        open_flag = 0;
        qDebug()<<"close success";
    }
}

void MainWindow::timerOut_slot(void)
{
    QStringList serial_Name_temp_list;

    if(open_flag == 1)
        return;

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        serial_Name_temp_list << info.portName();
    }

    if(serial_Name_temp_list != serial_Name_list)
    {
        ui->serial_number_comboBox->clear();
        serial_Name_list = serial_Name_temp_list;
        ui->serial_number_comboBox->addItems(serial_Name_list);
    }
}

void MainWindow::timer2Out_slot(void)
{
    uint8_t buf[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, 0x07, 0x00, 0x00, 0x0D, 0x0A};
    serial_write(buf, 10);
}

/* 开灯 */
void MainWindow::on_pushButton_clicked()
{
    if(open_flag == 1)
    {
        uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x05, 0x00, 0x09, 0x00, 0x00, 0x80, 0x0D, 0x0A};
        buf[8] |= ui->horizontalSlider->value();
        serial_write(buf, 11);
        close_flag = 0;
    }
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(true);
}

/* 关灯 */
void MainWindow::on_pushButton_2_clicked()
{
    if(open_flag == 1)
    {
        uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0D, 0x0A};
        buf[8] |= ui->horizontalSlider->value();
        serial_write(buf, 11);
        close_flag = 1;
    }
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
}

/* 调光 */
void MainWindow::on_horizontalSlider_sliderReleased()
{
    uint8_t value;
    value = ui->horizontalSlider->value();

    if(open_flag == 0)
        return;

    uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x05, 0x00, 0x09, 0x00, 0x00, 0x80, 0x0D, 0x0A};

    if(close_flag == 1)
        buf[8] &= 0x7f;

    buf[8] |= value;

    serial_write(buf, 11);

//    uint8_t *p = buf;
//    do
//    {
//        printf("0x%x", *p);
////        qDebug() << QString::number(*p, 16);
//    }while(*(p++) != 0x0A);
//    QByteArray data(1, value);
//    serial.write(data);
    qDebug() << value;
}

void MainWindow::on_open_file_pushButton_clicked()
{

    QString path = QFileDialog::getOpenFileName(this, tr("Open File"), ".", tr("Bin Files(*.bin)"));
    if(path.isNull())
        return;

    ui->file_name_lineEdit->setText(path);
    QFile file(path);
    file.open(QIODevice::ReadOnly);
    QByteArray array = file.readAll();
    file_len = array.size();
    memcpy(tx_data, array.data(), file_len);

    write_index = 0;
    ui->download_progressBar->setValue(write_index/file_len);
}

void MainWindow::on_download_pushButton_clicked()
{
    /* 烧录之前必须打开串口 */
    if(open_flag == 0)
    {
        QMessageBox::warning(NULL, "warning", "请打开串口！", "确定");
        return;
    }

    /* 烧录之前必须选择烧录文件 */
    if(ui->file_name_lineEdit->text().isEmpty())
    {
        QMessageBox::warning(NULL, "warning", "请选择需要烧录的文件！", "确定");
        return;
    }

    /* 烧录按钮变灰 */
    ui->download_pushButton->setEnabled(false);

    /* 显示进度条 */
    ui->download_progressBar->show();
    ui->download_progressBar->setValue(0);

    /* 写入的字节偏移量为0 */
    write_index = 0;

    /* 发送进入bootloader命令 */
    send_bootloader();

    /* 刷机开始 */
    start_flag = 1;
}
/* 串口写入函数 */
void MainWindow::serial_write(unsigned char *buf, int len)
{
    packet_id++;
    if(packet_id == 63)
        packet_id = 0;

    buf[5] = (unsigned char)packet_id;

    printf("write_serial_%d[", len);
    for(int i = 0; i < len; i++)
        printf("%0.2x ", buf[i]);
    printf("]\n");

    std::cout.flush();

    serial.write((const char *)buf, len);
}


/* 进入bootloader */
void MainWindow::send_bootloader(void)
{
    /* 进入BootLoader */
    unsigned char buf[11] = {0xEA, 0xEB, 0xEE, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x0D, 0x0A};

    serial_write(buf, 11);
}

/* 接收串口信号 */
void MainWindow::read_serial_slot(void)
{
    QByteArray read_array;
    char *rx_data;
    int len;

    read_array = serial.readAll();

    rx_data = read_array.data();
    len = read_array.size();

//    for(int i = 0; i < len; i++)
//        printf("%0.2x ", (uint8_t)rx_data[i]);
//    printf("]\n");
//std::cout.flush();

    if(rx_data[5] != 0x07)
        if(start_flag == 0)
            return;



    /* 校验命令 */
    if(rx_data[5] != 0x07)
        if(check_cmd((unsigned char *)rx_data, len) == 0)
            return;

//    for(int i = 0; i < len; i++)
//        printf("%0.2x ", (uint8_t)rx_data[i]);
//    printf("]\n");
//std::cout.flush();

    int protocol;
    protocol = rx_data[5];
    unsigned char buf[500] = {0xEA, 0xEB, 0xEE, 0x00, 0x2C + 90 ,0x00, 0x0C, 0x00, 0x00};
    uint16_t CheckSum = 0;

    uint8_t user_len = 36 + 90;
    switch(protocol)
    {
        case 10:
            if(check_ack((unsigned char *)rx_data) == 0)
                return;
            break;

        case 11:
//            send_download();

            write_index = 0;
            buf[13 + user_len] = 0x0D;
            buf[14 + user_len] = 0x0A;
            buf[9] = write_index / 256;
            buf[10] = write_index % 256;
            memcpy(buf + 10, tx_data + write_index, user_len);
            for(int j = 0; j < user_len; j++)
            {
                CheckSum +=  buf[11 + j];
            }
            buf[11 + user_len] = CheckSum / 256;
            buf[12 + user_len] = CheckSum % 256;
            serial_write((unsigned char *)buf, 15 + user_len);
            break;

        case 12:
            write_index += user_len;
            if(write_index <= file_len)
                ui->download_progressBar->setValue(write_index*100/file_len);
            else
                ui->download_progressBar->setValue(100);

            if(write_index < file_len)
            {
                int tx_len;

                if(write_index + user_len > file_len)
                {
                    tx_len = file_len - write_index;
                    buf[3] = (8 + tx_len) / 256;
                    buf[4] = (8 + tx_len) % 256;
                }
                else
                    tx_len = user_len;



                buf[13 + tx_len] = 0x0D;
                buf[14 + tx_len] = 0x0A;
                buf[9] = write_index / 256;
                buf[10] = write_index % 256;
                memcpy(buf + 10, tx_data + write_index, tx_len);
                for(int j = 0; j < tx_len; j++)
                {
                    CheckSum +=  buf[11 + j];
                }
                buf[11 + tx_len] = CheckSum / 256;
                buf[12 + tx_len] = CheckSum % 256;

                serial_write((unsigned char *)buf, 15 + tx_len);
            }
            else
            {
                /* 启动APP */
                unsigned char buf1[11] = {0xEA, 0xEB, 0xEE, 0x00, 0x04, 0x00, 0x0D, 0x00, 0x00, 0x0D, 0x0A};
                serial_write((unsigned char *)buf1, 11);
            }
            break;

        case 13:
            start_flag = 0;
            write_index = 0;
            ui->download_progressBar->setValue(0);
            ui->download_progressBar->hide();
            QMessageBox::information(NULL, "warning", "烧录成功！", "确定");
            ui->download_pushButton->setEnabled(true);
            break;

         case 07:
            v = *(float *)(rx_data + 8);
            c = *(float *)(rx_data + 12);
            p = *(float *)(rx_data + 16);
            e = *(float *)(rx_data + 20);
            v = (int)(v * 100) / 100.0;
            c = (int)(c * 1000) / 1000.0;
            p = (int)(p * 100) / 100.0;
//qDebug() << QString("%1").arg(v);
//            QString str_c = QString("%1").arg(c);
//            QString str_p = QString("%1").arg(p);
//            QString str_e = QString("%1").arg(e);
            ui->label_14->setText(QString("%1").arg(v));
            ui->label_15->setText(QString("%1").arg(c));
            ui->label_16->setText(QString("%1").arg(p));
            ui->label_17->setText(QString("%1").arg(e));
            break;
        default:
            qDebug() << "default";
            break;
    }
}

/* 校验cmd */
int MainWindow::check_cmd(unsigned char *buf, int len)
{
    int flag = 0;

    printf("read_serial_%d[", len);
    for(int i = 0; i < len; i++)
        printf("%0.2x ", buf[i]&0xFF);
    printf("]\n");
    std::cout.flush();

    if(buf[0] == 0xEA && buf[1] == 0xEB && buf[2] == 0xEE)
    {
        if(buf[3] == len - 6)
        {
            if(buf[len-2] == 0x0D && buf[len-1] == 0x0A)
            {
                flag = 1;
            }
        }
    }

    if(flag == 0)
    {
        start_flag = 0;
        write_index = 0;
        ui->download_progressBar->setValue(0);
        ui->download_progressBar->hide();
        QMessageBox::warning(NULL, "warning", "烧录失败！", "确定");
        ui->download_pushButton->setEnabled(true);
        return 0;
    }

    return 1;
}


/* 校验ack */
int MainWindow::check_ack(unsigned char *buf)
{
    int flag = 0;

    if((buf[4]&0x3F) == packet_id)
        flag = 1;

    if(flag == 0)
    {
        start_flag = 0;
        write_index = 0;
        ui->download_progressBar->setValue(0);
        ui->download_progressBar->hide();
        QMessageBox::warning(NULL, "warning", "烧录失败！", "确定");
        ui->download_pushButton->setEnabled(true);
        return 0;
    }

    return 1;
}




void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    ui->Dim_Value_label->setText(QString::number(value));
}

///* 设置灯具ID */
//void MainWindow::on_pushButton_3_clicked()
//{
//    uint8_t buf1[] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A};
//    uint8_t id = 0;
//    buf1[6] = id = ui->spinBox->value() / 256;
//    buf1[7] = id = ui->spinBox->value() % 256;
//    serial_write(buf1, 10);
//    qDebug() << id;
//}

/* 设置电力参数 */
void MainWindow::on_pushButton_4_clicked()
{

}

///* 获取电力参数 */
//void MainWindow::on_pushButton_5_clicked()
//{
//    uint8_t buf1[] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, 0x07, 0x00, 0x00, 0x0D, 0x0A};
//    serial_write(buf1, 10);
//}

void MainWindow::on_pushButton_5_clicked()
{
    uint8_t buf1[] = {0xEA, 0xEB, 0xEE, 0x05, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0D, 0x0A};
    uint16_t power = 0;
    buf1[8] = power = ui->lineEdit->text().toInt();
    serial_write(buf1, 11);
    qDebug() << power;
}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    uint32_t value;
    value = ui->lineEdit->text().toInt();
    if(value > 100)
        ui->lineEdit->setText(QString::number(100));
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    if(index == 3)
    {
        timer2.start(1000);
    }
    else
    {
        timer2.stop();
    }
}
